package com.fsd.admin.service.impl;

import java.io.*;
import java.util.*;
import javax.annotation.Resource;

import com.fsd.admin.service.F_formfieldService;
import com.fsd.core.util.BeanToMapUtil;
import com.gexin.fastjson.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.hibernate.Criteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.fsd.core.service.impl.BaseServiceImpl;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.ParametersUtil;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.F_form;
import com.fsd.admin.service.F_formService;
import com.fsd.admin.dao.F_formDao;

@Repository("f_formServiceImpl")
public class F_formServiceImpl extends BaseServiceImpl<F_form, String> implements F_formService{
    
    private static final Logger log = Logger.getLogger(F_formServiceImpl.class);
    private String depict = "";
    
    @Resource(name = "f_formDaoImpl")
	public void setBaseDao(F_formDao F_formDao) {
		super.setBaseDao(F_formDao);
	}
	
	@Resource(name = "f_formDaoImpl")
	private F_formDao objectDao;

    @Autowired
    private F_formfieldService formfieldService;
    
    /**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	@Override
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("f_deleted", "0"));
		c.addOrder(Order.asc("f_adddate"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				Disjunction dis = Restrictions.disjunction();
				dis.add(Restrictions.like("f_name", "%" + objectMap.get("title") + "%"));
				dis.add(Restrictions.like("f_displayname", "%" + objectMap.get("title") + "%"));
				c.add(dis);
			}
		}
		return objectDao.findPager(param , c);
	}
    
    /**
	 * 编辑对象
	 * @param obj
	 * @param employee
	 * @throws Exception
	 */
    @Override
	public void save(F_form obj, A_Employee employee) throws Exception{
        if(obj.getId() != null && !"".equals(obj.getId())){
            //修改
            F_form old_obj = objectDao.get(obj.getId());

			old_obj.setF_name(obj.getF_name());
			old_obj.setF_wordtemplate(obj.getF_wordtemplate());
			old_obj.setF_displayname(obj.getF_displayname());
			old_obj.setF_description(obj.getF_description());
			//设置修改日期
            old_obj.setF_lastupdatedate(this.getData());
			//设置修改用户id
			old_obj.setF_updateemployeename(employee.getId());
			//设置修改用户姓名
			old_obj.setF_updateemployeename(employee.getRealname());
            objectDao.update(old_obj);
        }else{
            //添加
			//设置主键
            obj.setId(this.getUUID());
			//设置添加日期
			obj.setF_adddate(this.getData());
			//设置添加用户id
			obj.setF_addemployeeid(employee.getId());
			//设置添加用户姓名
			obj.setF_addemployeename(employee.getRealname());
			//设置删除标志(true:已启用 false：未启用)
			obj.setF_status("false");
			//设置删除标志(0:正常 1：已删除)
			obj.setF_deleted("0");
			objectDao.save(obj);
        }
    }
    
    /**
	 * 删除对象
	 * @param parameters
	 * @throws Exception
	 */
	@Override
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		for (String id : dir) {
			F_form form = objectDao.get(id);
			form.setF_deleted("1");
			form.setF_lastupdatedate(this.getData());
			form.setF_updateemployeeid(employee.getId());
			form.setF_updateemployeename(employee.getUpdateemployeename());
			objectDao.update(form);
		}
	}
    
    /**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	@Override
	public F_form getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		F_form obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}

	/**
	 * 修改状态
	 * @param parameters
	 * @param employee
	 * @throws Exception
	 */
	@Override
	public void updateEnabledObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);

		String isEnabled = objectMap.get("isenabled").toString();
		ArrayList<String> idList = (ArrayList<String>) objectMap.get("ids");

		for (String id : idList) {
			F_form form = objectDao.get(id);
			form.setF_status(isEnabled);
			objectDao.update(form);
		}
	}

	/**
	 * 保存表单设计
	 * @param parameters
	 * @param employee
	 * @throws Exception
	 */
	@Override
	public void saveFormDesign(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);

		//获得表单ID查询表单对象
		String formid = objectMap.get("formid").toString();
		F_form form = this.get(formid);

		String parse_form = objectMap.get("parse_form").toString();
		Map<String, Object> map = gs.fromJson(parse_form, Map.class);

		Map<String, Object> datas = (Map<String, Object>)map.get("add_fields");
		ArrayList<Map<String, Object>> list = (ArrayList<Map<String, Object>>) map.get("data");
		formfieldService.saveFormField(form, list);

		String template = (String)map.get("template");
		String parseHtml = (String)map.get("parse");

		form.setF_originalhtml(template);
		form.setF_parsehtml(parseHtml.replaceAll("\\{\\|\\-", "").replaceAll("-\\|}", ""));

		form.setF_updateemployeename(employee.getUpdateemployeename());
		form.setF_updateemployeeid(employee.getId());
		form.setF_lastupdatedate(this.getData());
		objectDao.update(form);
	}

	/**
	 * 保存表单数据
	 * @param parameters
	 * @throws Exception
	 */
	public void saveForm(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		Map taskMap = (Map) objectMap.get("taskjson");
		Map formMap = (Map) objectMap.get("formjson");
		Integer taskid = (int)Double.parseDouble(taskMap.get("taskid").toString());
		String formid = taskMap.get("formid").toString();
		String employeeid = taskMap.get("employeeid").toString();
		F_form tbl_form = objectDao.get(formid);
		String querySql = "select * from f_tbl_" + tbl_form.getF_name() + " where f_employeeid='"+employeeid+"'";
		List objList = objectDao.queryBySql(querySql);
		if(objList.size() != 0){
			String updateSql = "update f_tbl_" + tbl_form.getF_name() + " set ";
			for(Object obj : formMap.keySet()){
				updateSql += obj + "='" + formMap.get(obj) + "', ";
			}
			updateSql += "f_updatetime='"+this.getData()+"' where f_employeeid='"+employeeid+"'";
			objectDao.executeSql(updateSql);
		}else{
			String addSql = "insert into f_tbl_" + tbl_form.getF_name() + " (id, ";
			for(Object obj : formMap.keySet()){
				addSql += obj + ", ";
			}
			addSql += "f_formid, f_taskid, f_updatetime, f_employeeid) values ('"+this.getUUID()+"', ";
			for(Object obj : formMap.keySet()){
				addSql += "'" + formMap.get(obj) + "', ";
			}
			addSql += "'"+formid+"', '"+taskid+"', '"+this.getData()+"', '"+employeeid+"');";
			objectDao.executeSql(addSql);
		}
	}

	/**
	 * 加载表单数据
	 * @param parameters
	 * @throws Exception
	 */
	public Map<String, Object> getObjectForm(ParametersUtil parameters) throws Exception{
		Map<String, Object> resultMap = new HashMap<>();
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		String employeeid = objectMap.get("employeeid").toString();
		String formid = objectMap.get("formid").toString();
		F_form tbl_form = objectDao.get(formid);
		String querySql = "select * from f_tbl_" + tbl_form.getF_name() + " where f_employeeid='"+employeeid+"'";
		List objList = objectDao.queryBySql(querySql);
		Map<String, Object> map;
		if(objList.size() != 0){
			JSONObject json = JSONObject.fromObject(objList.get(0));
			map = (Map) JSON.parse(json.toString());
			resultMap = BeanToMapUtil.transformUpperCase(map);
		}
		return resultMap;
	}

	/**
	 * 获取党员发起人信息
	 * @param proc_inst_id
	 * @return
	 * @throws Exception
	 */
	public String getInitUser(String proc_inst_id) throws Exception {
		String sql = "select START_USER_ID_ from act_hi_procinst where PROC_INST_ID_=?";
		List list = objectDao.queryBySql(sql, proc_inst_id);
		if(list.size() != 0){
			Map<String, Object> map = (Map<String, Object>) list.get(0);
			return (String) map.get("START_USER_ID_");
		}else{
			return "";
		}
	}

	/**
	 * Word表单导出
	 */
	public Map<String, String> exportForm(ParametersUtil parameters, String rootPath, String httpRootPath) throws Exception {
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		Map taskMap = (Map) objectMap.get("taskjson");
		Map formMap = (Map) objectMap.get("formjson");
		String formid = taskMap.get("formid").toString();
		F_form tbl_form = objectDao.get(formid);
		String path = tbl_form.getF_wordtemplate();
		String tempPath = "uploadfiles/temp/"+tbl_form.getF_displayname()+".doc";
		String templatePath = rootPath+path;  //模板地址
		if (StringUtils.isEmpty(templatePath)) {
			throw new BusinessException("请先绑定对应表单模板！");
		}
		File file = new File(templatePath);
		if (!file.exists()) {
			throw new BusinessException("模板文件不存在！");
		}
		InputStream fis = new FileInputStream(file);
		HWPFDocument doc = new HWPFDocument(fis);
		Range range = doc.getRange();
		for(Object obj : formMap.keySet()){
			range.replaceText("{" + obj + "}", (String) formMap.get(obj));
		}
		OutputStream os = new FileOutputStream(rootPath+tempPath);
		try {
			doc.write(os);
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			fis.close();
			os.close();
		}
		String httpUrl = httpRootPath+tempPath;
		Map<String, String> map = new HashMap<>();
		map.put("httpUrl", httpUrl);
		return map;
	}
}
